<template>
  <div class="relative leading-[0px]">
    <!-- 单行 -->
    <input
      v-if="type === TYPE_TEXT"
      v-model="text"
      :maxlength="max"
      class="border-gray-200 min-h-[30px] dark:border-zinc-600 dark:bg-zinc-800 duration-100 dark:text-zinc-400 border outline-0 py-0.6 px-1 text-sm rounded-sm focus:border-blue-400 w-full"
      type="text"
    />
    <!-- 多行 -->
    <textarea
      v-if="type === TYPE_TEXTAREA"
      maxlength="max"
      v-model="text"
      rows="10"
      class="border-gray-200 dark:border-zinc-600 dark:bg-zinc-800 duration-100 dark:text-zinc-400 border outline-0 p-1 text-sm rounded-sm focus:border-blue-400 w-full"
    ></textarea>
    <!-- 最大长度 -->
    <span
      v-if="max"
      class="absolute right-1 bottom-0.5 text-xs text-zinc-400"
      :class="{ 'text-red-700': currentText === parseInt(max) }"
      >{{ currentText }} / {{ max }}
    </span>
  </div>
</template>

<script>
import { computed, watch } from '@vue/runtime-core'
import { useVModel } from '@vueuse/core'

// 单行输入
const TYPE_TEXT = 'text'
// 多行输入
const TYPE_TEXTAREA = 'textarea'
</script>

<script setup>
const props = defineProps({
  // 1.model
  modelValue: {
    type: String,
    required: true
  },
  // 2.类型
  type: {
    type: String,
    default: TYPE_TEXT,
    validator(val) {
      const arr = [TYPE_TEXT, TYPE_TEXTAREA]
      const result = arr.includes(val)
      if (!result) {
        throw new Error(`类型只允许在${arr.join('、')}中进行选择`)
      }
      return result
    }
  },
  // 最大字符数
  max: {
    type: [String, Number]
  }
})

const emits = defineEmits(['update:modelValue'])

const text = useVModel(props)

// 输入的字符数
const currentText = computed(() => {
  return text.value.length
})

watch(
  () => props.type,
  (val) => {
    console.log(val)
  }
)
</script>
